package com.lgx.right.dao.impl;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.lgx.common.basic.dao.GeneralDao;
import com.lgx.common.basic.dao.GeneralJdbcDao;

import com.lgx.common.exception.DataException;
import com.lgx.common.tree.TreeUtils;
import com.lgx.common.tree.easyui.TreeModel;
import com.lgx.right.dao.IPermissionDao;
import com.lgx.right.entity.Permission;

/**
 * 
 * 
 * @author acer
 *
 */
@Component("permissionDao")
public class PermissionDao extends GeneralDao implements IPermissionDao {

	protected Logger log = Logger.getLogger(this.getClass());
	
	@Autowired
	private GeneralJdbcDao baseDao;
	
	public GeneralJdbcDao getBaseDao() {
		return baseDao;
	}

	public void setBaseDao(GeneralJdbcDao baseDao) {
		this.baseDao = baseDao;
	}

	@Transactional
	public Permission createPermission(Permission permission)
			throws DataException {
		this.getHibernateTemplate().save(permission);
		log.info("[创建权限]:"+permission.getId());
		return permission;
	}

	@Transactional
	public Permission updatePermission(Permission permission)
			throws DataException {
		this.getHibernateTemplate().update(permission);
		log.info("[更新权限]:"+permission.getId());
		return permission;
	}

	@Transactional
	public void deletePermission(Permission permission) throws DataException {
		log.info("[删除权限]:"+permission.getId());
		this.getHibernateTemplate().delete(permission);
	}

	public void deletePermission(long id) throws DataException {
		this.deletePermission(this.findPermissionById(id));
		log.info("[删除权限]:"+id);
	}

	public Permission findPermissionById(long id) {
		return this.getHibernateTemplate().get(Permission.class, id);
	}

	@SuppressWarnings("unchecked")
	public List<Permission> findPermissionList(String sql) {
		return this.getHibernateTemplate().find(sql);
	}

	@SuppressWarnings("unchecked")
	public List<Permission> findPermissionJdbcList(String sql) {
		return (List<Permission>) this.baseDao.queryJdbcForList(sql, Permission.class);
	}

	@SuppressWarnings("unchecked")
	public List<Permission> findPermissionList() {
		String sql = "SELECT PE.* FROM TS_PERMISSION PE ORDER BY PE.LAYERORDER";
		List<Permission> ps = (List<Permission>) this.baseDao.queryJdbcForList(sql, Permission.class);
		return (List<Permission>) TreeUtils.addChildren(ps, null, null);
	}

	@SuppressWarnings("unchecked")
	public List<Permission> findPermissionList(long userId,String type) {
		String sql =" SELECT PE.* FROM TS_PERMISSION PE "+
					" INNER JOIN TS_ROLE_PERMISSION RP ON RP.PERMISSION_ID = PE.ID "+
					" INNER JOIN TS_USER_ROLE UR ON RP.ROLE_ID = UR.ROLE_ID "+
					" WHERE PE.ISDELETE = '0' AND UR.USER_ID =  " + userId;
		if(!StringUtils.isEmpty(type))
		{
			sql += " AND PE.TYPE = '"+type+"'";
		}
		return (List<Permission>) this.baseDao.queryJdbcForList(sql, Permission.class);
	}

	public List<TreeModel> findPermissionTreeList() {
		String sql = "SELECT PE.* FROM TS_PERMISSION PE WHERE PE.TYPE='0' ORDER BY PE.LAYERORDER";
		@SuppressWarnings("unchecked")
		List<Permission> ps = (List<Permission>) this.baseDao.queryJdbcForList(sql, Permission.class);
		return  TreeUtils.changeObjectToTreeModelAddChildren(ps, new String[]{"id","name","layerOrder"}, new String[]{"id","text","layerOrder"}, "children", "layerOrder");
	}

	/**
	 * 为角色添加权限
	 * 检索全部权限表，按照级联返回
	 */
	@SuppressWarnings("unchecked")
	public List<TreeModel> findPermissionRoleTreeList(long roleId) {
		String sql =" select distinct pe.id as id,pe.name as text,pe.layerOrder as layerOrder,case when rp.role_id is not null then 'true' else null end as checked  "+
					" from ts_permission pe "+
					" left join ts_role_permission rp on pe.id = rp.permission_id and rp.role_id = "+ roleId+
					" order by pe.layerOrder asc ";
		List<TreeModel> models = (List<TreeModel>) this.baseDao.queryJdbcForList(sql, TreeModel.class);
		return (List<TreeModel>) TreeUtils.addChildren(models, null, null);
	}

	@SuppressWarnings("unchecked")
	public List<Permission> findPermissionByIds(String ids) {
		
		String sql = "select distinct pe from Permission pe where ";
		
		sql += " (exists (from Permission p where p.id in ("+ids+") and p.type = '1' and p.parent = pe.id)";
		
		sql += " or ";
		
		sql += " ( pe.id in ("+ids+") and pe.level != '2'))";
		
		
		sql += " order by pe.layerOrder asc";
		return this.getHibernateTemplate().find(sql);
	}
}
